package mrms.api.web.controllers;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.AllArgsConstructor;
import mrms.api.entity.UserEntity;
import mrms.api.repository.UserRepository;
import mrms.api.repository.DeptRepository;
import mrms.api.web.authentication.Encipher;
import mrms.api.web.dto.FogetPasswordDto;
import mrms.api.web.dto.UpdateUserPasswordDto;
import mrms.api.web.dto.VerifyDto;
import mrms.api.web.utils.MessageSender;
import mrms.api.web.utils.PicUtil;
import mrms.api.web.utils.Result;
import mrms.api.web.utils.UserState;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * @author lenchu
 * @date 2019/02/16
 */
@RestController
@AllArgsConstructor
public class UserController {
    private final HashMap<String,String> hashMap=new HashMap<>();

    private final UserRepository userRepository;
    private final DeptRepository deptRepository;

    @GetMapping("/user/{id}/pic")
    public Result findUserPicById(@PathVariable String id) throws IOException {
        Optional<UserEntity> optionalUserEntity = userRepository.findById(id);
        if (optionalUserEntity.isPresent()) {
            UserEntity userEntity = optionalUserEntity.get();
            String faceBase64String = PicUtil.baseurl(userEntity.getFaceuri());
            return Result.success(faceBase64String);
        } else {
            return Result.error("无此用户");
        }
    }



    @GetMapping("/user/{dept}/dept")
    public Result findUserByDept(@PathVariable String dept){
        List<UserEntity> userEntities=userRepository.findAllByDept(deptRepository.findById(dept).get());
        userEntities.stream().forEach(userEntity -> {
            userEntity.setFaceuri(null);
            userEntity.setFeature(null);
        });
        return Result.success(userEntities);
    }


    @GetMapping("/a/user")
    public Result findAllUserByState(@RequestParam(defaultValue = "1") Integer state,
                                     Pageable pageable) {
        Page<UserEntity> page;
        if (state > 0) {
            page = userRepository.findAll(pageable);
        } else {
            page = userRepository.findAllByEnabled(state, pageable);
        }
         page.stream().forEach(userEntity -> {
//             try {
//                 userEntity.setFaceuri(PicUtil.baseurl(userEntity.getFaceuri()));
//             } catch (IOException e) {
//                 e.printStackTrace();
//             }
             userEntity.setFeature(null);
         });
        return Result.success(page);
    }

    @PutMapping("/user")
    public Result updateUser(@RequestAttribute UserEntity user,
                             @RequestBody UpdateUserPasswordDto updateUserPasswordDto) {
        String encryptedOldPassword = Encipher.encryptPasswordWithMD5(updateUserPasswordDto.getOldPassword());
        if (encryptedOldPassword.equals(user.getPassword())) {
            user.setPassword(Encipher.encryptPasswordWithMD5(updateUserPasswordDto.getNewPassword()));
            return Result.success(userRepository.save(user));
        } else {
            return Result.error("旧密码错误");
        }
    }

    @GetMapping("/user/{name}/like")
    public Result findByNameLike(@PathVariable String name) {
        return Result.success(userRepository.findAllByNameLikeAndEnabled("%" + name + "%", UserState.ENABLED));
    }

    @DeleteMapping("/a/user/{id}")
    public Result deleteById(@PathVariable String id) {
        Optional<UserEntity> optionalUserEntity = userRepository.findById(id);
        if (optionalUserEntity.isPresent()) {
            UserEntity userEntity = optionalUserEntity.get();
            userEntity.setEnabled(UserState.DISABLED);
            return Result.success(userRepository.save(userEntity));
        } else {
            return Result.error("无此用户");
        }
    }

    @PutMapping("/a/user/{id}/enable")
    public Result enableUser(@PathVariable String id) {
        Optional<UserEntity> optionalUserEntity = userRepository.findById(id);
        if (optionalUserEntity.isPresent()) {
            UserEntity userEntity = optionalUserEntity.get();
            userEntity.setEnabled(UserState.ENABLED);
            return Result.success(userRepository.save(userEntity));
        } else {
            return Result.error("无此用户");
        }
    }

    @GetMapping("/user/getcode/{tel}")
    public Result getCode(@PathVariable String tel) throws JsonProcessingException {
        UserEntity userEntity=userRepository.findUserEntityByTel(tel);
        String code=MessageSender.send(tel);
        hashMap.put(tel,code);
        return Result.success("发送验证码成功");
    }

    @PostMapping("/user/verify")
    public Result forgetPwd(@RequestBody VerifyDto verifyDto){
        if (verifyDto.getCode().equals(hashMap.get(verifyDto.getTel()))){
            hashMap.remove(verifyDto.getTel());
            return Result.success("验证成功");
        }
        else return Result.error("验证码失败");
    }


    @PostMapping("/user/forgetpwd")
    public Result updateUserPwd(@RequestBody FogetPasswordDto fogetPasswordDto) {
        UserEntity userEntity=userRepository.findUserEntityByTel(fogetPasswordDto.getTel());
        userEntity.setPassword(Encipher.encryptPasswordWithMD5(fogetPasswordDto.getPassword()));
            return Result.success(userRepository.save(userEntity));
        }





}
